package com.briup.web;

import com.briup.bean.*;
import com.briup.service.ICalllogService;
import com.briup.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author adam
 * @date 2023/2/26
 */
@Controller
public class UserController {
    @Autowired
    IUserService userService;
    @Autowired
    ICalllogService calllogService;

    @PostMapping("login")
    public String login(String name, String password, @RequestParam(defaultValue = "19313925217") String tel, @RequestParam(defaultValue = "2021-01") String year, HttpServletRequest req, HttpServletResponse response) {

        String msg = "登录成功";
        try {
            User user = userService.login(name, password);
            //登录成功,将 customer放到session中
            req.getSession().setAttribute("user", user);
            req.setAttribute("msg", msg);
            List<CallLog> logs = calllogService.queryMonthDatas(tel, year);
            Plan plan = calllogService.queryCurrRemainder(tel, year);
            CallPer callPer = calllogService.queryPerRemainder(tel, year);
            List<Consume> list = calllogService.queryMonthConsume(tel, year);
            Consume consume = calllogService.queryYearConsume(tel, year);
            req.setAttribute("callLogs",logs);
            req.setAttribute("plan",plan);
            req.setAttribute("callPer",callPer);
            req.setAttribute("list",list);
            req.setAttribute("consume",consume);
            req.setAttribute("rand1",java.lang.Math.round(java.lang.Math.random() * 100) );
            req.setAttribute("rand2",java.lang.Math.round(java.lang.Math.random() * 1000) );
            return "index";
        } catch (Exception e) {
            //登录失败
            e.printStackTrace();
            msg = e.getMessage();
            return "login";
        }


    }

    @GetMapping("logout")
    public String logout(HttpServletRequest req, HttpServletResponse resp) {
        HttpSession session = req.getSession();
        //销毁session
        session.invalidate();
        return "login";
    }

    @PostMapping("register")
    public String register(User user, HttpServletRequest req) {
        try {
            userService.register(user);
            req.setAttribute("msg", "注册成功");
            return "login";
        } catch (Exception e) {
            req.setAttribute("msg", e.getMessage());
            return "register";
        }

    }
}
